import React, { useEffect, useState, useRef } from 'react'
import { useModel, history } from '@umijs/max'
import { ProTable } from '@ant-design/pro-components'
import {
  App,
  Button,
  Radio,
  InputNumber,
  Form,
  Space,
  Result,
  Spin,
  Alert,
  ConfigProvider,
  Steps,
  Statistic,
  Image
} from 'antd'
import { TransactionOutlined } from '@ant-design/icons'
import zhCN from 'antd/locale/zh_CN'
import styles from './WithdrawalApply.less'
import dayjs from 'dayjs'

const { Countdown } = Statistic
const statusColorMap = {
  '-1': '#F53F3F',
  1: '#FD5F02',
  2: '#FD5F02',
  3: '#00B42A'
}

const WithdrawalApply = () => {
  const { WithdrawPreload, ApplyWithdraw, CancelWithDraw } = useModel('Agent')
  const { modal, message } = App.useApp()
  const [isLoading, setIsLoading] = useState(false)
  const [step, setStep] = useState(0)
  const [accountData, setAccountData] = useState({})
  const [recordData, setRecordData] = useState({})
  const [initialData, setInitialData] = useState({ account: 1 })
  const [deadline, setDeadline] = useState(0)
  const [applyForm] = Form.useForm()

  useEffect(() => {
    checkData()
  }, [])

  const checkData = async () => {
    setIsLoading(true)
    const res = await WithdrawPreload()
    setIsLoading(false)

    if (res) {
      const { record_exist, withdraw_detail } = res
      if (record_exist) {
        setRecordData(withdraw_detail)
        const { status } = withdraw_detail
        if (status === 1 || status === 2) {
          setStep(1)
        } else if (status === 3 || status === -1) {
          if (status === 3) {
            const { surplus } = withdraw_detail
            setDeadline(dayjs(dayjs().valueOf() + surplus * 1000))
          }
          setStep(2)
        }
      } else {
        setStep(0)
      }
      setAccountData(res)
    }
  }

  const confirmApply = async () => {
    await applyForm.validateFields()
    const values = applyForm.getFieldsValue()

    setIsLoading(true)
    let params = {
      ...values
    }
    const res = await ApplyWithdraw(params)
    setIsLoading(false)
    if (res) {
      message.success('已处理')
      checkData()
    }
  }

  const cancelApply = async () => {
    setIsLoading(true)
    const res = await CancelWithDraw({ id: recordData.id })
    setIsLoading(false)
    if (res) {
      message.success('已取消')
      checkData()
    }
  }

  return (
    <ConfigProvider locale={zhCN}>
      <div className={styles.pageContainer}>
        <h2 className={styles.title}>{'申请提现'}</h2>
        <Spin tip='加载中...' spinning={isLoading}>
          <div className={styles.apply_wrapper}>
            <Steps
              current={step}
              items={[
                {
                  title: '提交申请',
                  description: '提交提现申请'
                },
                {
                  title: '平台受理',
                  description: '等待平台处理提现申请'
                },
                {
                  title: '提现结果',
                  description: '提现申请的处理结果'
                }
              ]}
            />

            {step !== 2 ? (
              <>
                <Alert
                  showIcon
                  className={styles.alert_block}
                  type='warning'
                  message='提现说明'
                  description={
                    step === 0 ? (
                      <div>
                        1. 每 30 天累计可申请提现 1 次,每次允许提现最低金额为 100元 ，金额可精确到分。
                        <br />
                        2. 暂仅支持人工打款（到账时间以实际为准），若有疑问，请联系平台相关人员。
                      </div>
                    ) : (
                      <div>
                        1. 平台已受理您的提现申请，若审核未通过，提现金额将返还至可提现账户中。
                        <br />
                        2. 若长时间未处理提现申请，请及时联系平台相关人员。
                      </div>
                    )
                  }
                ></Alert>

                <Alert
                  showIcon
                  className={styles.alert_block}
                  type='info'
                  message={
                    <Space>
                      <div className={styles.alert_money}>
                        <div>
                          可提现金额: <span>{accountData.total_surplus_withdraw_amount}元</span>
                        </div>
                        <div>
                          提现冻结中: <span>{accountData.total_withdraw_freeze_amount}元</span>
                        </div>
                      </div>
                    </Space>
                  }
                ></Alert>
              </>
            ) : (
              <Result
                status={recordData.status === 3 ? 'success' : 'error'}
                title={recordData.status === 3 ? '处理完成' : '拒绝提现'}
                subTitle={
                  recordData.status === 3 ? '提现申请已经处理完成' : '平台未通过您的提现申请，如有疑问请于平台方沟通'
                }
              />
            )}

            {step === 0 ? (
              <Form preserve={false} form={applyForm} name='applyForm' initialValues={initialData}>
                <Form.Item name='account' label='收款账户' rules={[{ required: true, message: '请选择收款账户' }]}>
                  <Radio.Group>
                    <Radio value={1}>{accountData.account}</Radio>
                  </Radio.Group>
                </Form.Item>

                <Form.Item
                  name='withdraw_amount'
                  label='提现金额'
                  rules={[{ required: true, message: '请输入提现金额' }]}
                >
                  <InputNumber
                    precision={2}
                    addonAfter='元'
                    min={100}
                    max={Number(accountData.total_surplus_withdraw_amount)}
                  />
                </Form.Item>
              </Form>
            ) : (
              <div className={styles.info_block}>
                <div className={styles.info_content}>
                  <div className={styles.info_title}>提交信息</div>
                  <div className={styles.info_line}>
                    <div className={styles.info_label}>提现金额：</div>
                    <div className={styles.info_value} style={{ color: '#165DFF' }}>
                      {recordData.withdraw_amount}元
                      {recordData.status === 1 || recordData.status === 2 ? '（提现冻结中）' : ''}
                    </div>
                  </div>
                  <div className={styles.info_line}>
                    <div className={styles.info_label}>账户类型：</div>
                    <div className={styles.info_value}>{recordData.withdraw_type_desc}</div>
                  </div>
                  <div className={styles.info_line}>
                    <div className={styles.info_label}>收款账号：</div>
                    <div className={styles.info_value}>{recordData.collection_account}</div>
                  </div>
                  <div className={styles.info_line}>
                    <div className={styles.info_label}>收款人姓名：</div>
                    <div className={styles.info_value}>{recordData.collection_name}</div>
                  </div>
                  <div className={styles.info_line}>
                    <div className={styles.info_label}>提交时间：</div>
                    <div className={styles.info_value}>{recordData.apply_time}</div>
                  </div>
                </div>
                <div className={styles.info_content}>
                  <div className={styles.info_title}>受理情况</div>
                  <div className={styles.info_line}>
                    <div className={styles.info_label}>处理结果：</div>
                    <div className={styles.info_value} style={{ color: statusColorMap[recordData.status.toString()] }}>
                      {recordData.status_desc}
                    </div>
                  </div>
                  <div className={styles.info_line}>
                    <div className={styles.info_label}>处理人员：</div>
                    <div className={styles.info_value}>{recordData.op_name || '-'}（处理审核人员名称）</div>
                  </div>
                  <div className={styles.info_line}>
                    <div className={styles.info_label}>处理时间：</div>
                    <div className={styles.info_value}>{recordData.op_time || '-'}（点击处理提现的时间）</div>
                  </div>
                  {recordData.status === 3 ? (
                    <>
                      <div className={styles.info_line}>
                        <div className={styles.info_label}>处理凭证：</div>
                        <div className={styles.info_value}>
                          <Space>
                            {recordData.payment_voucher.map(i => {
                              return <Image width={60} preview src={i}></Image>
                            })}
                          </Space>
                        </div>
                      </div>
                      <div className={styles.info_line}>
                        <div className={styles.info_label}>处理意见：</div>
                        <div className={styles.info_value}>{recordData.remarks || '-'}</div>
                      </div>
                    </>
                  ) : recordData.status === -1 || recordData.status === 3 ? (
                    <div className={styles.info_line}>
                      <div className={styles.info_label}>处理意见：</div>
                      <div className={styles.info_value}>{recordData.remarks || '-'}</div>
                    </div>
                  ) : null}
                </div>
              </div>
            )}

            <Space>
              {step === 0 ? (
                <Button onClick={confirmApply} type='primary'>
                  确认提现
                </Button>
              ) : step === 1 ? (
                <Button type='primary' onClick={cancelApply}>
                  取消提现
                </Button>
              ) : step === 2 ? (
                recordData.status === -1 ? (
                  <Button type='primary' onClick={() => setStep(0)}>
                    重新申请
                  </Button>
                ) : (
                  <Button type='primary' disabled={recordData.surplus}  onClick={() => setStep(0)}>
                    再次发起
                    {recordData.surplus ? (
                      <span>（剩余{<Countdown value={deadline} format='D 天 H 时 m 分 s 秒' />}可再次发起）</span>
                    ) : (
                      ''
                    )}
                  </Button>
                )
              ) : null}
            </Space>
          </div>
        </Spin>
      </div>
    </ConfigProvider>
  )
}

export default WithdrawalApply
